#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include <string>

int pattern_match(const std::string &str, const std::string &pattern, size_t str_begin = 0, size_t pattern_begin = 0 )
{
	if( str.length() == str_begin && pattern.length() == pattern_begin ) 
		return 0;
	else if( str.length() == str_begin && pattern.length() != pattern_begin ) 
		return -1;
	else if( str.length() != str_begin && pattern.length() == pattern_begin ) 
		return -1;

	switch( pattern.at( pattern_begin ) ) {
		case '?':
			return pattern_match( str, pattern, str_begin + 1 , pattern_begin + 1 );
			break;
		case '*':
			if( pattern_match( str, pattern, str_begin + 1 , pattern_begin  ) == 0 )
				return 0;
			else
				return pattern_match( str, pattern, str_begin, pattern_begin + 1 );
			break;
	default:
			if( pattern.at( pattern_begin ) == str.at( str_begin ) )
				return pattern_match( str, pattern, str_begin + 1 , pattern_begin + 1 );
			else
				return -1;
		break;
	}
	return 0;
}

void print_useage( void )
{
	printf( "Pattern match program, support '?' and '*', '\\' is not supported.\n"
			"Useage:\n"
			"\tpattern_match pattern input_string\n"
			"Example:\n"
			"\tpattern_match 'a*b' 'abc'\n");
}

int main(int argc, char *argv[] )
{
	if( 3 == argc ) {
		if( pattern_match( argv[2], argv[1]) == 0 ) {
			printf( "matched\n" );
		}
		else {
			printf( "unmatched\n" );
		}
	}
	else {
		print_useage();
		return 1;
	}
	return 0;
}
